/**
 * Description:信息模板转换工具
 * @author huxh
 * @date 2012-01-15
 */
package com.cr.backbone.util;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.Application;

import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import sun.security.jca.GetInstance;

import com.cr.backbone.model.MessageTemplate;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class UtilsTemplateFreemarker {
	
	private static UtilsTemplateFreemarker instance=null;
	
	private boolean load=true;//默认加载
	private Map<String, MessageTemplate> messageTemplates=new HashMap<String, MessageTemplate>();
	
	/**
	 * 
	 */
	public UtilsTemplateFreemarker() {
		initTemplates();
		load=false;
	}
	
	public static UtilsTemplateFreemarker getInstance() {
		if(instance==null)
			instance=new UtilsTemplateFreemarker();
		return instance;
	}
	
	public void reload(){
		if(!load)
			return;
		
		initTemplates();
		
		load=false;
	}
	
	public void initTemplates(){
		messageTemplates =null;
		
	}
	
	
	public static void main(String[] args) throws IOException, TemplateException {
		String templateContextStr="你好，我是:\"${name}\"!";
		Reader reader=new StringReader(templateContextStr);
		Configuration cfg= new Configuration();
		Template template =new Template("utilStringTemplate",reader,cfg);
		Writer out=new StringWriter();
		
		
		Map<String, String> templateContextParamsMap=new HashMap<String, String>();
		String value="胡湘华";
		templateContextParamsMap.put("name", value);
		//		template.process(templateContextParamsMap, out);
		template.process(templateContextParamsMap, out);
		
		System.out.println(out.toString());

		
		String textTemplate="<html><body>${name}</body></html>";
		System.out.println(UtilsTemplateFreemarker.getInstance().getMessage(textTemplate, templateContextParamsMap));
	}

	/**
	 * @methodDescribe
	 * @param textTemplate
	 * @param paramsTemplate
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-14 
	 */
	public String getMessage(String textTemplate,
			Map<String, String> templateContextParamsMap) {
		try {
			String templateContextStr=textTemplate;
			Reader reader=new StringReader(templateContextStr);
			Configuration cfg= new Configuration();
			Template template;
			template = new Template("utilStringTemplate",reader,cfg);
			Writer out=new StringWriter();
			
			//模板+内容解析为输出流
			template.process(templateContextParamsMap, out);
			return out.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
}

